import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { throwError, Observable, Subscriber } from 'rxjs';


// 中文文档 https://www.fenxianglu.cn/highlightjs/docs/api/
@Injectable({
  providedIn: 'root'
})
export class HighLightService {
  private highLightScriptSrc = `//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js`;

  private highLightCssHref = `//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/default.min.css`;

  // private highLightLineNumbersOnLoadScriptSrc = `//cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.8.0/highlightjs-line-numbers.min.js`;

  constructor(@Inject(DOCUMENT) private document: Document, @Inject(PLATFORM_ID) private platformId: any) {}

  initHighLightScript(
    prismScriptSrc?: string,
    prismCssHref?: string
    //  highLightLineNumbersOnLoadScriptSrc?: string
  ) {
    if (!isPlatformBrowser(this.platformId)) {
      return throwError(() => '请在浏览器中打开');
    }
    return new Observable(observer => {
      const prismScriptEl = this.document.createElement('script');
      prismScriptEl.src = prismScriptSrc || this.highLightScriptSrc;
      prismScriptEl.onload = () => {
        this.initHighLightCss(
          observer,
          prismCssHref || this.highLightCssHref
          // highLightLineNumbersOnLoadScriptSrc || this.highLightLineNumbersOnLoadScriptSrc
        );
      };
      this.document.head.appendChild(prismScriptEl);
    });
  }

  initHighLightCss(
    observer: Subscriber<unknown>,
    prismCssHref: string
    // , highLightLineNumbersOnLoadScriptSrc: string
  ) {
    const prismCssEl = this.document.createElement('link');
    prismCssEl.href = prismCssHref;
    prismCssEl.rel = 'stylesheet';
    prismCssEl.onload = () => {
      // this.initHighLightLineNumbersOnLoadScript(observer, highLightLineNumbersOnLoadScriptSrc);
      observer.next(true);
      observer.complete();
    };
    this.document.head.appendChild(prismCssEl);
  }

  // initHighLightLineNumbersOnLoadScript(observer: Subscriber<unknown>, highLightLineNumbersOnLoadScriptSrc: string) {
  //   const highLightLineNumbersOnLoadScriptEl = this.document.createElement('script');
  //   highLightLineNumbersOnLoadScriptEl.src = highLightLineNumbersOnLoadScriptSrc;
  //   highLightLineNumbersOnLoadScriptEl.onload = () => {
  // observer.next(true);
  // observer.complete();
  //     console.log('添加成功');
  //   };
  //   this.document.head.appendChild(highLightLineNumbersOnLoadScriptEl);
  // }
}
